import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Savepoint;
import java.sql.Statement;

public class TransactionStudy {
    private static Connection s_pConnect;
    private static Statement s_pStatement;
    private static Savepoint s_pSavePoint;

    public static void main(String[] args) {
        try {
            Class.forName(Const.JDBC_DRIVER);
            s_pConnect = DriverManager.getConnection(Const.MYSQL_URL, Const.USER_NAME, Const.USER_PASSWORD);

            /*关闭自动提交，改为手动提交的方式*/
            s_pConnect.setAutoCommit(false);

            /*可以设置保存点,回滚时可以指定具体的回滚点*/
            s_pSavePoint = s_pConnect.setSavepoint("Savepoint1");

            s_pStatement = s_pConnect.createStatement();
            String strInsertSql = "INSERT INTO simpleTable VALUE(null, '老王', 40, '打牌')";
            int iRows = s_pStatement.executeUpdate(strInsertSql);

            /*这里为了触发异常，触发回滚，异常必须出现在 commit 之前*/
            int a = 1 / 0;

            /*需要手动提交*/
            s_pConnect.commit();

            if (iRows > 0) {
                System.out.println("插入数据成功");
            } else {
                System.out.println("插入数据失败");
            }

        } catch (Exception e) {
            System.out.println("触发回滚...");
            try {
//                s_pConnect.rollback();

                /*回到具体的保存点*/
                s_pConnect.rollback(s_pSavePoint);
            } catch (Exception e1) {
                e1.printStackTrace();
            }

        } finally {
            try {
                if (s_pStatement != null) {
                    s_pStatement.close();
                }

                if (s_pConnect != null) {
                    s_pConnect.close();
                }
            } catch (Exception e) {

            }
        }
    }
}
